package net.root.plain.main;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.WindowManager;
import android.widget.Button;

public class AlarmActivity extends Activity{
	WakeLock m_sleep_lock = null;
	Button btn;
	MediaPlayer mMediaPlayer;
	Thread t;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.alarm);
		
		PowerManager power = (PowerManager) getSystemService(Context.POWER_SERVICE);
		// 화면이 꺼지 않도록 제어할 수 있는 권리를 얻는다.
		m_sleep_lock = power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
				"NonSleepActivity");
		// 화면이 꺼지지 않도록 설정한다.
		m_sleep_lock.acquire();

		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
						| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
						| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
						| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

		AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
		am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
		
		t = new Thread(new Runnable() {
			@SuppressWarnings("unused")
			@Override
			public void run() {
				// TODO Auto-generated method stub
				RingtoneManager ringtoneManager = new RingtoneManager(
						AlarmActivity.this);
				Uri alarmRingtoneUri = RingtoneManager
						.getDefaultUri(RingtoneManager.TYPE_ALARM);

				mMediaPlayer = new MediaPlayer();
				try {
					mMediaPlayer.setDataSource(AlarmActivity.this,
							alarmRingtoneUri);
					mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
					mMediaPlayer.setLooping(true);
					mMediaPlayer.prepare();
					mMediaPlayer.start();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		t.start();
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (m_sleep_lock.isHeld()) {
			// 화면 제어를 해제한다.
			m_sleep_lock.release();
		}
		t.interrupt();
		mMediaPlayer.release();
	}
}
